package logic

import (
	"context"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"order_srv/internal/model"
	"order_srv/internal/svc"
	"order_srv/order_proto"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateOrderLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateOrderLogic {
	return &UpdateOrderLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdateOrderLogic) UpdateOrder(in *order_proto.UpdateOrderRequest) (*order_proto.Empty, error) {
	// todo: add your logic here and delete this line
	var order model.Order
	tx := model.DB.Begin()
	res := tx.Where(&model.Order{OrderSn: in.OrderSn}).First(&order)
	if res.RowsAffected == 0 {
		tx.Rollback()
		return nil, status.Errorf(codes.NotFound, "订单不存在")
	}

	order.PayType = in.PayType
	order.Status = in.Status
	order.OrderSn = in.OrderSn
	order.TradeNo = in.TradeNo

	save := model.DB.Save(order)
	if save.Error != nil {
		tx.Rollback()
		return nil, status.Errorf(codes.Internal, "修改订单信息失败")
	}
	tx.Commit()
	return &order_proto.Empty{}, nil
}
